import {Component, ElementRef, Renderer2} from '@angular/core';
import {ApesField} from '@shared/ui-zorro/src/types/apes-field';
import {Events} from '@core/services/events/Events';
import {ExpressionService} from '@core/services/expression/ExpressionService';
import {SubjectService} from '@core/services/events/subject.service';
import {ApiService} from '@core/services/http/api.service';
import {SearchService} from '@core/services/search.service';

import {
  getText,
  getValueUsingField,
  replaceAll,
  type,
} from '../../../../utils/utils';

@Component({
  selector: 'formly-field-search-input',
  template: `
    <apes-input-group apesSearch [apesSuffix]="suffixIconButton">
      <input apes-input [placeholder]="to.placeholder" [formControl]="formControl" [readonly]="readonly"
             [disabled]="to.disabled" [formlyAttributes]="field" [value]="_value">
    </apes-input-group>

    <ng-template #suffixIconButton>
        <i apes-icon apesType="search"></i>
    </ng-template>
  `,
  styles: [
    `
      i {
        cursor: pointer;
      }
    `
  ]
})
export class FormlyFieldSearchInput extends ApesField {

  _value: any = '';
  apesConfig: any;
  searchFormId: string;
  searchSelectApi: string;
  multiple = false;
  private _domain;

  constructor(protected apiService: ApiService, protected events: Events, protected expressionService: ExpressionService, protected subject: SubjectService,
              protected elementRef: ElementRef, protected renderer: Renderer2, protected searchService: SearchService) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit() {
    this.apesConfig = this.extend(this.to);
    this.searchFormId = this.to.searchFormId;
    this.multiple = this.to.multiple === 'true' || false;
    if (this.to['domain']) {
      this.to.domain = replaceAll(this.to.domain, '\'', '');
      this._domain = JSON.parse(this.to.domain);
    }
  }

  get readonly() {
    return this.to.readonly;
  }

  getValueFormatter(): string {
    return this.to.valueFormatter || 'value.name';
  }

  formatter(value: any, expression: string) {
    // for(let i=0, len=result.length; i<len; i++ ){
    //   let format = this.formatter(result[i], this.getValueFormatter());
    //   if( this._value.length === 0 ){
    //     this._value += format;
    //   } else {
    //     this._value += "," + format;
    //   }
    // }
    if (!this.multiple) {
      return this.expressionService.evaluate(expression, {
        context: this.formState,
        model: this.formState.model,
        value: value
      });
    } else {
      this._value =  this._value && this._value.length > 0 ? this._value : [];
      // for(let i=0, len=result.length; i<len; i++ ){
      //   let format = this.formatter(result[i], this.getValueFormatter());
      //   if( this._value.length === 0 ){
      //     this._value += format;
      //   } else {
      //     this._value += "," + format;
      //   }
      // }
    }

  }

  // onSearch() {
  //   this._value = '';
  //   const field = this.to.componentRef.field.key;
  //   this.searchService.openDialog(this.to.api, false,(result: any) => {
  //     if (result && result.length > 0) {

  //       for(let i=0, len=result.length; i<len; i++ ){
  //         let format = this.formatter(result[i], this.getValueFormatter());
  //         console.log(format);
  //         if( this._value.length === 0 ){
  //           this._value += format;
  //         } else {
  //           this._value += "," + format;
  //         }
  //       }

  //       let temp = {};
  //       temp[field] = result;
  //       this.form.patchValue(temp);
  //     }
  //   }).subscribe();
  // }

  onSearch() {
    const key = this.to.componentRef.field.key;
    const options = {multiple: this.multiple}; // 声明查询条件
    if (this._domain) {
      const group = this.fillField(this._domain, true);
      console.log(JSON.stringify(group));
      if ( !(group.filters.length === 0 && group.groups.length === 0 )) {
        options['domain'] = group   ;
      }
    }
    this.searchService.openDialog(this.searchFormId, options, (result: any) => {
      this._value = ''; // 初始化显示值
      if (result && result.length > 0) {
        for (let i = 0, len = result.length; i < len; i++) {
          const format = this.formatter(result[i], this.getValueFormatter());
          if (this._value.length === 0) {
            this._value += format;
          } else {
            this._value += ',' + format;
          }
        }
        const temp = {};
        temp[key] =  this.multiple ? result && result.length ?  result : []
          : result && result.length ?  result[0] : {};
        this.form.patchValue(temp);
      }
    }).subscribe();
  }

  protected extend(data: any) {
    const result = {};
    for (const key in data) {
      const value = data[key];
      result[key] = value;
    }
    return result;
  }


    // 对传入的域进行处理
    private fillField(domain: any, searchFlag: Boolean = false) {
      let result;
      if (type(domain) === 'object') {
        result = {};
      } else {
        result = [];
      }
      for (const key in domain) {
        let value = domain[key];
        const t = type(value);
        if (t === 'object') {
          value = this.fillField(value, searchFlag);
        } else if (t === 'array') {
          value = [...this.fillField(value, searchFlag)];
        } else {
          if (t === 'string') {
            const text = getText(value);
            if (text) {
                value = getValueUsingField(this.formState, text, true);
            }
            if (text === 'value') {
              if (searchFlag)  return;
              value = this._value;
            } else {
              value = getValueUsingField(this.formState, text, true);
            }
          }
        }

        let val = value;
        if ( type(value) === 'array' ) {
          if (type(val) === 'array') {
            // 对解析出的数据做出筛选
            val = val.filter((elem) =>  elem !== undefined);
          }
          value = val;
        } else if ( type(value) === 'object' && val.filters ) {
          if ( val.filters.length === 0 ) {
            if ( val.groups.length === 0 ) {
              val = [];
            } else {
              val.filters = val.groups;
              val.groups = [];
            }
          }
        }

        if ( key === 'groups' && val[0] && val[0].length === 0) {
          result[key] = [];
        } else {
          result[key] = val;
        }
      }

      return result;
    }
}
